package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQueryObject;
import cn.wolfcode.luowowo.comment.repository.ITravelRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {
    @Autowired
    private MongoTemplate mongoTemplate; //处理比较复杂的操作
    @Autowired
    private ITravelRepository mongeRepository; //处理简单的crud

    @Override
    public TravelComment saveOrUpdate(TravelComment travelComment) {
        //createTime
        if(travelComment.getId() == null){
            travelComment.setCreateTime(new Date());
        }
        if(travelComment.getRefComment() != null && StringUtils.hasLength(travelComment.getRefComment().getId())){
            //查询引用的评论设置进去
            travelComment.setRefComment(this.get(travelComment.getRefComment().getId()));
        }
        mongeRepository.save(travelComment);
        return travelComment;
    }

    //查询单个评论
    @Override
    public TravelComment get(String id) {
        return mongeRepository.findById(id).get();
    }

    @Override
    public List<TravelComment> getCommentTop10() {
        Query query = new Query();
        //排序条件
        query.with(new Sort(Sort.Direction.DESC, "createTime"));
        //分页条件:前十条
        query.with(PageRequest.of(0, 10));
        List<TravelComment> comments = mongoTemplate.find(query, TravelComment.class);
        return comments;
    }


    @Override
    public Page<TravelComment> query(TravelCommentQueryObject qo) {
        //查询封装对象
        Query query = new Query();
        //查询条件
        Criteria criteria = null;
        if(qo.getTravelId() != -1){
            criteria = Criteria.where("travelId").is(qo.getTravelId());
        }else {
            criteria = Criteria.where("travelId").ne(qo.getTravelId());
        }
        //添加查询条件
        query.addCriteria(criteria);
        //查询条数
        long count = mongoTemplate.count(query, TravelComment.class);
        //优化
        if(count == 0){
            return Page.empty();
        }

        //添加排序条件
        query.with(new Sort(Sort.Direction.DESC, "createTime"));
        //添加分页条件
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        query.with(pageable);

        //查询评论数据
        List<TravelComment> list = mongoTemplate.find(query, TravelComment.class);
        return new PageImpl<>(list, pageable, count);
    }
}
